<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Article extends Model
{

    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'update_time';

    protected static function init()
    {
    	//插入之前放图片
      Article::event('before_insert',function($article){
          if($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'.'/'.'article');
                if($info){
                    // $thumb=ROOT_PATH . 'public' . DS . 'uploads'.'/'.$info->getExtension();
                    $filePath=DS .'uploads'.'/'.'article'.'/'.$info->getSaveName();
                    $thumb = str_replace("\\", "/", $filePath);
                    $article['thumb']=$thumb;
                }
            }
      });

        //修改数据之前先修改图片路劲并删除图片
         Article::event('before_update', function ($article) {
            $file = request()->file('thumb');
        	if (!empty($file)) {
        		$arts = Article::find($article->id);
        		$thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
        		if (file_exists($thumbpath)) {
        			@unlink($thumbpath);
        		}
				$file = request()->file('thumb');
				$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.'/'.'article');
				if ($info) {
					$filePath=DS .'uploads'.'/'.'article'.'/'.$info->getSaveName();
                    $thumb = str_replace("\\", "/", $filePath);
					$article['thumb']=$thumb;
				}
			}
        });

         //删除数据之前先删除缩略图
         Article::event('before_delete', function ($article) {
        		$arts = Article::find($article->id);
        		$thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
        		if (file_exists($thumbpath)) {
        			@unlink($thumbpath);
			}
        });
    }
}
